package com.atguigu.gulimall.order.interceptor;

import com.atguigu.common.constant.auth.AuthConstant;
import com.atguigu.common.vo.MemberResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 
 * @ClassName LoginUserInterceptor
 * @Description 从session中获取了登录信息（redis中），封装到了ThreadLocal中
 * @Author xufb
 * @Date 2024/4/28 17:27:33
 * @Version 1.0
 */
@Component
@Slf4j
public class LoginUserInterceptor implements HandlerInterceptor {

    public static ThreadLocal<MemberResponseVo> loginUser = new ThreadLocal<>();

    // 请求到达控制器之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 放行无需登录的请求
        String uri = request.getRequestURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();// 匹配器
        boolean match = antPathMatcher.match("/order/order/status/**", uri);// 查询订单消息
        boolean match1 = antPathMatcher.match("/payed/**", uri);// 支付回调
        log.info("登录拦截请求：{}", uri);
        if (match || match1) {
            return true;
        }
        // 从session中获取了登录信息（redis中）
        MemberResponseVo attribute = (MemberResponseVo) request.getSession().getAttribute(AuthConstant.LOGIN_USER);
        if (attribute != null) {
            // 已登录，放行
            // 封装用户信息到threadLocal
            loginUser.set(attribute);
            return true;
        } else {
            // 未登录，跳转登录页面
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.println("<script>alert('请先进行登录，再进行后续操作！');location.href='http://auth.xfb.com/login.html'</script>");
            return false;
        }
    }
}
